<script setup lang="tsx">
import { ref, onMounted, onBeforeUnmount, watch, shallowRef, defineProps } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
const props = defineProps({
  value: {
    type: Array,
    required: true
  },
  newLat: {
    type: Object,
    default: () => ({})
  }
})

const map = shallowRef(null)
const driving = ref(null)

onMounted(() => {
  initMap()
})

onBeforeUnmount(() => {
  if (map.value) {
    map.value.destroy()
  }
})

const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: '4026bddc19aa18708a4c449dab30b760'
  }
  AMapLoader.load({
    key: '58963ffc424fa9d569a619e53c5594c4', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.PolyLine', 'AMap.Driving'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map.value = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式
        zoom: 14, // 初始化地图级别
        center: [114.419018, 35.041692] // 初始化地图中心点位置
      })
    })
    .catch((e) => {
      console.log(e)
    })
}
const getDriving = async (val) => {
  console.log(val)
  if (driving.value) {
    driving.value.clear() // 清除驾车规划线
    map.value.clearMap()
  }
  val.unshift(props.newLat)
  const points = val.map((point) => new AMap.LngLat(point.long, point.lat))
  const routes = []

  // 清除地图上的所有覆盖物（包括之前的线和标记）
  map.value.clearMap()

  for (let i = 0; i < points.length - 1; i += 15) {
    const start = points[i]
    const end = points[Math.min(i + 15, points.length - 1)]
    const waypoints = points.slice(i + 1, Math.min(i + 15, points.length - 1))
    const segment = await new Promise((resolve, reject) => {
      driving.value = new AMap.Driving({
        policy: 0,
        map: map.value,
        panel: 'panel',
        hideMarkers: true
      })
      driving.value.search(start, end, { waypoints }, (status, result) => {
        if (status === 'complete') {
          resolve(result.routes[0])
        } else {
          reject(result)
        }
      })
    })
    routes.push(segment)
  }

  // 添加起点图标
  const startMarker = new AMap.Marker({
    position: points[0],
    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
    map: map.value,
    offset: new AMap.Pixel(-12, -12)
  })
  const startInfoWindow = new AMap.InfoWindow({
    content: val[0].name,
    offset: new AMap.Pixel(0, -30)
  })
  startMarker.on('click', () => {
    startInfoWindow.open(map.value, startMarker.getPosition())
  })

  // 添加途经点图标
  for (let i = 1; i < points.length - 1; i++) {
    const wayMarker = new AMap.Marker({
      position: points[i],
      icon: new AMap.Icon({
        size: new AMap.Size(24, 24), // 图标大小
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png',
        imageSize: new AMap.Size(24, 24) // 图标大小
      }),
      offset: new AMap.Pixel(-12, -12), // 图标偏移量（调整至图标中心）
      map: map.value
    })
    const wayInfoWindow = new AMap.InfoWindow({
      content: val[i].name,
      offset: new AMap.Pixel(0, -30)
    })
    wayMarker.on('click', () => {
      wayInfoWindow.open(map.value, wayMarker.getPosition())
    })
  }

  // 添加终点图标
  const endMarker = new AMap.Marker({
    position: points[points.length - 1],
    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
    map: map.value,
    offset: new AMap.Pixel(-12, -12)
  })
  const endInfoWindow = new AMap.InfoWindow({
    content: val[val.length - 1].name,
    offset: new AMap.Pixel(0, -30)
  })
  endMarker.on('click', () => {
    endInfoWindow.open(map.value, endMarker.getPosition())
  })
  map.value.setFitView()
}

watch(
  () => props.value,
  (newValue) => {
    if (newValue.length > 0) {
      setTimeout(() => {
        getDriving(newValue)
      }, 3000)
    }
  },
  {
    immediate: true
  }
)
</script>
<template>
  <div>
    <div id="container"></div>
    <div id="panel"></div>
  </div>
</template>
<style lang="less" scoped>
#container {
  width: 100%;
  height: calc(100vh - 100px);
}
#panel {
  position: absolute;
  background-color: white;
  max-height: 50%;
  overflow-y: auto;
  top: 310px;
  right: 10px;
  width: 280px;
}
</style>
